package com.open.capacity.reimburse.service.impl;

import com.open.capacity.reimburse.entity.StdTrafficAllowance;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.user.model.SysArea;
import com.open.capacity.user.service.SysAreaService;
import com.open.capacity.user.service.SysUserService;
import com.open.capacity.utils.DateUtil;
import com.open.capacity.utils.StringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.open.capacity.commons.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

import org.apache.commons.collections4.MapUtils;

import com.open.capacity.reimburse.entity.StdMealAllowance;
import com.open.capacity.reimburse.dao.StdMealAllowanceDao;
import com.open.capacity.reimburse.service.StdMealAllowanceService;


@Service
public class StdMealAllowanceServiceImpl implements StdMealAllowanceService {

    @Autowired
    private StdMealAllowanceDao stdMealAllowanceDao;

    @Autowired
    private SysAreaService areaService;

    /**
     * 添加
     *
     * @param stdMealAllowance
     */
    public int save(StdMealAllowance stdMealAllowance) {
        stdMealAllowance.setId(UUIDUtils.getOriginalUUIDWithoutBar());

        SysArea province = areaService.findById(stdMealAllowance.getProvinceId());
        stdMealAllowance.setProvinceName(province.getAreaName());

        String[] cityIds = stdMealAllowance.getCityId().split(",");
        String cityName = "";
        for (String c : cityIds) {
            SysArea city = areaService.findById(c);
            if (StringUtil.isEmpty(cityName)) {
                cityName += city.getAreaName();
            } else {
                cityName += "," + city.getAreaName();
            }
        }
        stdMealAllowance.setCityName(cityName);

        if (StringUtil.isNotEmpty(stdMealAllowance.getCountyId())) {
            String[] countyIds = stdMealAllowance.getCountyId().split(",");
            String countyName = "";
            for (String c : countyIds) {
                SysArea county = areaService.findById(c);
                if (StringUtil.isEmpty(countyName)) {
                    countyName += county.getAreaName();
                } else {
                    countyName += "," + county.getAreaName();
                }
            }
            stdMealAllowance.setCountyName(countyName);
        }

        stdMealAllowance.setUpdateTime(new Date());
        return stdMealAllowanceDao.save(stdMealAllowance);
    }

    /**
     * 修改
     *
     * @param stdMealAllowance
     */
    public int update(StdMealAllowance stdMealAllowance) {
        SysArea province = areaService.findById(stdMealAllowance.getProvinceId());
        stdMealAllowance.setProvinceName(province.getAreaName());

        String[] cityIds = stdMealAllowance.getCityId().split(",");
        String cityName = "";
        for (String c : cityIds) {
            if (StringUtil.isNotEmpty(c)) {
                SysArea city = areaService.findById(c);
                if (StringUtil.isEmpty(cityName)) {
                    cityName += city.getAreaName();
                } else {
                    cityName += "," + city.getAreaName();
                }
            }
        }
        stdMealAllowance.setCityName(cityName);

        if (StringUtil.isNotEmpty(stdMealAllowance.getCountyId())) {
            String[] countyIds = stdMealAllowance.getCountyId().split(",");
            String countyName = "";
            for (String c : countyIds) {
                if (StringUtil.isNotEmpty(c)) {
                    SysArea county = areaService.findById(c);
                    if (StringUtil.isEmpty(countyName)) {
                        countyName += county.getAreaName();
                    } else {
                        countyName += "," + county.getAreaName();
                    }
                }
            }
            stdMealAllowance.setCountyName(countyName);
        }

        stdMealAllowance.setUpdateTime(new Date());
        return stdMealAllowanceDao.update(stdMealAllowance);
    }


    /**
     * 删除
     *
     * @param id
     */
    public int delete(String id) {
        return stdMealAllowanceDao.delete(id);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public StdMealAllowance findById(String id) {
        return stdMealAllowanceDao.findById(id);
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<StdMealAllowance> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<StdMealAllowance> list = stdMealAllowanceDao.findAll(params);
        PageInfo<StdMealAllowance> pageInfo = new PageInfo(list);

        return PageResult.<StdMealAllowance>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<StdMealAllowance> findAll(Map<String, Object> params) {
        return stdMealAllowanceDao.findAll(params);
    }

    /**
     * 获取伙食补贴总额
     *
     * @param userId        当事人
     * @param followUserids 随行人员
     * @param destination   目的地
     * @param startDate     开始日期
     * @param endDate       结束日期
     * @return
     */
    @Override
    public BigDecimal getMoney(String userId, String followUserids, Integer persons, String destination, Date startDate, Date endDate) {
        BigDecimal standard = BigDecimal.ZERO;
        String[] destinationArr = destination.split("/");
        String provinceId = destinationArr.length > 0 ? destinationArr[0] : "";
        String cityId = destinationArr.length > 1 ? destinationArr[1] : "";
        String countyId = destinationArr.length > 2 ? destinationArr[2] : "";
        int personCounts = (StringUtil.isEmpty(followUserids) ? 0 : followUserids.split(",").length) + 1;
        //判断手工填写的人数是否比随行人员少，以少的为准
        if (persons < personCounts) {
            personCounts = persons;
        }
        Map<String, Object> params = new HashMap<>();
        List<StdMealAllowance> list = stdMealAllowanceDao.findAll(params);

        boolean flag;
        if (CollectionUtils.isNotEmpty(list)) {
            StdMealAllowance item = list.get(0);

            //判断是否属于不参与补贴城市
            if (StringUtil.isNotEmpty(item.getProvinceId()) && provinceId.equals(item.getProvinceId())) {
                if (StringUtil.isEmpty(item.getCityId()) || (StringUtil.isNotEmpty(item.getCityId()) && StringUtil.isNotEmpty(cityId) && item.getCityId().contains(cityId))) {
                    if (StringUtil.isEmpty(item.getCountyId()) || (StringUtil.isNotEmpty(item.getCountyId()) && StringUtil.isNotEmpty(countyId) && item.getCountyId().contains(countyId))) {
                        return standard;
                    }
                }
            }

            if (item.getCategory().equals(1)) {//按天计算
                int days = DateUtil.getBetweenDay(startDate, endDate);
                if (days <= 0) {
                    days = 1;
                }
                standard = item.getTotalMoney().multiply(BigDecimal.valueOf(days)).multiply(BigDecimal.valueOf(personCounts));
            } else { //按时间段计算
                long d = DateUtil.dateDiff(startDate, endDate, "d");
                long h = DateUtil.dateDiff(startDate, endDate, "h");
                standard = (item.getFirstMoney().add(item.getSecondMoney()).add(item.getThirdMoney())).multiply(BigDecimal.valueOf(d)).multiply(BigDecimal.valueOf(personCounts));

                Calendar startCal = Calendar.getInstance();
                startCal.setTime(startDate);
                int startHour = startCal.get(Calendar.HOUR_OF_DAY );
                int startMinute = startCal.get(Calendar.MINUTE);
                String startStr = (startHour < 10 ? "0" + startHour : startHour) + ":" + (startMinute < 10 ? "0" + startMinute : startMinute) ;;
                Calendar endCal = Calendar.getInstance();
                endCal.setTime(endDate);
                int endHour = endCal.get(Calendar.HOUR_OF_DAY);
                int endMinute = endCal.get(Calendar.MINUTE);
                String endStr = (endHour < 10 ? "0" + endHour : endHour) + ":" + (endMinute < 10 ? "0" + endMinute : endMinute) ;
                if (startStr.compareTo(item.getFirstTime()) <= 0 && (h % 24) > 2) {
                    standard = standard.add(item.getFirstMoney().multiply(BigDecimal.valueOf(personCounts)));
                }
                if (startStr.compareTo(item.getSecondTime()) <= 0 && (h % 24) > 2) {
                    standard = standard.add(item.getSecondMoney().multiply(BigDecimal.valueOf(personCounts)));
                }
                if (startStr.compareTo(item.getThirdTime()) <= 0 && endStr.compareTo(item.getThirdTime()) >= 0) {
                    standard = standard.add(item.getThirdMoney().multiply(BigDecimal.valueOf(personCounts)));
                }

            }
        }
        return standard;
    }

    /**
     * 校验伙食补助是否超标
     *
     * @param userId        当事人
     * @param followUserids 随行人员
     * @param destination   目的地
     * @param startDate     开始日期
     * @param endDate       结束日期
     * @param money         金额
     * @return
     */
    @Override
    public String verify(String userId, String followUserids, Integer persons, String destination, Date startDate, Date endDate, BigDecimal money) {
        String error_msg = "";
        String[] destinationArr = destination.split("/");
        String provinceId = destinationArr.length > 0 ? destinationArr[0] : "";
        String cityId = destinationArr.length > 1 ? destinationArr[1] : "";
        String countyId = destinationArr.length > 2 ? destinationArr[2] : "";
        int personCounts = (StringUtil.isEmpty(followUserids) ? 0 : followUserids.split(",").length) + 1;
        //判断手工填写的人数是否比随行人员少，以少的为准
        if (persons < personCounts) {
            personCounts = persons;
        }
        Map<String, Object> params = new HashMap<>();
        List<StdMealAllowance> list = stdMealAllowanceDao.findAll(params);

        boolean flag;
        if (CollectionUtils.isNotEmpty(list)) {
            StdMealAllowance item = list.get(0);
            BigDecimal standard = BigDecimal.ZERO;

            //判断是否属于不参与补贴城市
            if (StringUtil.isNotEmpty(item.getProvinceId()) && provinceId.equals(item.getProvinceId())) {
                if (StringUtil.isEmpty(item.getCityId()) || (StringUtil.isNotEmpty(item.getCityId()) && StringUtil.isNotEmpty(cityId) && item.getCityId().contains(cityId))) {
                    if (StringUtil.isEmpty(item.getCountyId()) || (StringUtil.isNotEmpty(item.getCountyId()) && StringUtil.isNotEmpty(countyId) && item.getCountyId().contains(countyId))) {
                        error_msg = "<p>⊙ 该地区不参与伙食补助，请核实。</p>";
                        return error_msg;
                    }
                }
            }

            if (item.getCategory().equals(1)) {//按天计算
                int days = DateUtil.getBetweenDay(startDate, endDate);
                if (days <= 0) {
                    days = 1;
                }
                standard = item.getTotalMoney().multiply(BigDecimal.valueOf(days)).multiply(BigDecimal.valueOf(personCounts));
            } else { //按时间段计算
                long d = DateUtil.dateDiff(startDate, endDate, "d");
                long h = DateUtil.dateDiff(startDate, endDate, "h");
                standard = (item.getFirstMoney().add(item.getSecondMoney()).add(item.getThirdMoney())).multiply(BigDecimal.valueOf(d)).multiply(BigDecimal.valueOf(personCounts));

                Calendar startCal = Calendar.getInstance();
                startCal.setTime(startDate);
                int startHour = startCal.get(Calendar.HOUR_OF_DAY );
                int startMinute = startCal.get(Calendar.MINUTE);
                String startStr = (startHour < 10 ? "0" + startHour : startHour) + ":" + (startMinute < 10 ? "0" + startMinute : startMinute) ;;
                Calendar endCal = Calendar.getInstance();
                endCal.setTime(endDate);
                int endHour = endCal.get(Calendar.HOUR_OF_DAY);
                int endMinute = endCal.get(Calendar.MINUTE);
                String endStr = (endHour < 10 ? "0" + endHour : endHour) + ":" + (endMinute < 10 ? "0" + endMinute : endMinute) ;
                if (startStr.compareTo(item.getFirstTime()) <= 0 && (h % 24) > 2) {
                    standard = standard.add(item.getFirstMoney().multiply(BigDecimal.valueOf(personCounts)));
                }
                if (startStr.compareTo(item.getSecondTime()) <= 0 && (h % 24) > 2) {
                    standard = standard.add(item.getSecondMoney().multiply(BigDecimal.valueOf(personCounts)));
                }
                if (startStr.compareTo(item.getThirdTime()) <= 0 && endStr.compareTo(item.getThirdTime()) >= 0) {
                    standard = standard.add(item.getThirdMoney().multiply(BigDecimal.valueOf(personCounts)));
                }

            }

            flag = money.compareTo(standard) <= 0;
            if (!flag) {
                DecimalFormat decimalFormat = new DecimalFormat("###,###.00");
                error_msg = "<p>⊙ 伙食补助费用超标, 补贴合计不得超过" + decimalFormat.format(standard) + "元</p>";
            }
        }
        return error_msg;
    }

}
